﻿using ExcelConfig;
using SignetKA.utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SignetKA
{
    public partial class StartupForm : Form
    {
        public StartupForm()
        {
            InitializeComponent();
            refresh_select();
            LoadDefaultSignet();
        }

        internal string FilePath { get; set; }
        /// <summary>
        /// 新增
        /// </summary>
        private void button1_Click(object sender, EventArgs e)
        {
            var file = SysFast.PickFile("(图片)|*.png|(图片)|*.jpg|(图片)|*.bmp");
            if (string.IsNullOrEmpty(file)) return;
            var image = ColorTool.ScaleToRect(Image.FromFile(file), pictureBox1.ClientRectangle);
            //image = ColorTool.RemoveColorByHSV(image, Color.White, 1f, 0.2f, 0.13f);
            image = ColorTool.RemoveColor(image, Color.White);
            pictureBox1.Image = image;
            textBox2.Text = Path.GetFileName(file);
            FilePath = file;
            this.ShowPanel(p_add);
            textBox1.Focus();
        }

        /// <summary>
        /// 完成新增    
        /// </summary>
        private void button2_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBox1.Text)) return;

            var password = textBox1.Text;

            var dir = AppConfig.Text("印章目录");
            var path = Path.Combine(dir, $"{Guid.NewGuid().ToString()}.tfc");

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            AppConfig.WriteText("默认印章", path);
            AppConfig.WriteText(Path.GetFileName(path), textBox2.Text);
            var bag= EncryptTool.MakeKeyIV(password);
            using (var stream = File.Open(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                stream.Position = 0;
                var ouput = EncryptTool.SM4Encryption.Encrypt(EncryptTool.StreamToByteArray(stream), bag.key_tag, bag.iv_tag);
                using (var out_sr = File.Open(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite))
                {
                    var writer = new BinaryWriter(out_sr);
                    writer.Write(bag.key);
                    writer.Write(ouput);
                    writer.Write(bag.iv);
                    writer.Write(bag.key_tag);
                    writer.Flush();
                }
            }
            pictureBox1.Image = null;

            textBox1.Text = string.Empty;
            textBox2.Text = string.Empty;

            this.ShowPanel(p_select);
            refresh_select();
        }

        public void ShowPanel(Panel p)
        {
            foreach (var comp in Controls)
            {
                if (comp is Panel pitem)
                {
                    if (pitem == p) pitem.Show();
                    else pitem.Hide();
                }
            }
        }
        public void refresh_select()
        {
            var dir = AppConfig.Text("印章目录");
            lb_yz.Items.Clear();
            if (Directory.Exists(dir))
            foreach(var file in Directory.EnumerateFiles(dir))
            {
                var name = AppConfig.Text(Path.GetFileName(file));
                if (string.IsNullOrEmpty(name)) continue;
                lb_yz.Items.Add($"{name}; {Path.GetFileName(file)}");
            }
        }

        internal string SelectPath { get; set; }
        internal byte[] SelectKey { get; set; } = new byte[16];
        internal byte[] SelectKeyTag { get; set; } = new byte[16];
        /// <summary>
        /// 印章路径
        /// </summary>
        public string SignetPath { get; internal set; }
        /// <summary>
        /// 密码
        /// </summary>
        public string Pwd { get; internal set; }
        private void lb_yz_SelectedIndexChanged(object sender, EventArgs e)
        {
            var list = sender as ListBox;
            if (list.SelectedIndex == -1) return;
            var item = list.Items[list.SelectedIndex] as string;
            var filename = item.Split(new char[] { ';' }, 2).Last().Trim();
            var dir = AppConfig.Text("印章目录");
            var path = Path.Combine(dir, filename);

            using (var file = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                file.Position = 0;
                file.Read(this.SelectKey, 0, 16);
                file.Position = file.Length - 16;
                file.Read(this.SelectKeyTag, 0, 16);
            }
            this.SelectPath = path;
            this.ShowPanel(p_pass);
            this.tb_pass.Focus();
        }
        private void LoadDefaultSignet()
        {
            var defaultSignet = AppConfig.Text("默认印章");
            if (string.IsNullOrEmpty(defaultSignet)) return;
            if (File.Exists(defaultSignet))
            {

                using (var file = File.Open(defaultSignet, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    file.Position = 0;
                    file.Read(this.SelectKey, 0, 16);
                    file.Position = file.Length - 16;
                    file.Read(this.SelectKeyTag, 0, 16);
                }
                this.SelectPath = defaultSignet;
                this.ShowPanel(p_pass);
                this.tb_pass.Focus();
            }
        }
        private void tb_pass_TextChanged(object sender, EventArgs e)
        {
            var obj = sender as TextBox;
            var pwd = obj.Text;

            if (EncryptTool.VerityPwd(pwd, SelectKey, SelectKeyTag)){

                this.SignetPath = this.SelectPath;
                this.Pwd = pwd;
                AppConfig.WriteText("默认印章", this.SignetPath);
                this.Close();
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            this.ShowPanel(p_select);
        }
    }
}
